import React, { useState, useRef } from 'react'
import { LockOutlined, UserOutlined, SyncOutlined } from '@ant-design/icons';
import { Button, Form, Input, Space, message } from 'antd';
import axios from '../../api/axios';
import url from '../../api/url';
import Captcha from '../../components/Captcha';
import './Nor.css'
import { useHistory } from 'react-router-dom/cjs/react-router-dom';
import { useDispatch } from 'react-redux';
import { saveToken, saveMenus } from '@/store/userSlice'

export default function NormalLogin() {
  const capRef = useRef()
  const history = useHistory()
  const dispatch = useDispatch()
  let [key1, setKey1] = useState('')
  const setKey = (key) => {
    setKey1(key)
  }
  const onFinish = (values) => {
    values.key = key1
    axios.post(url.pwdlogin, values).then(res => {
      if (res.data.errNo === 0) {
        dispatch(saveToken(res.data.context.jwt))
        dispatch(saveMenus(res.data.context.acl))
        message.success(res.data.message, 1, () => {
          history.push("/dashboard")//登录成功后跳转到首页
        })
      } else {
        message.error(res.data.errText, 1)
        capRef.current.getCode()
      }
    })
  };

  return (
    <div>
      <Form
        name="normal_login"
        className="login-form"
        initialValues={{
          remember: true,
        }}
        onFinish={onFinish} // 提交表单且数据验证成功后回调事件
      >
        <Form.Item
          name="username"
          rules={[
            {
              required: true,
              message: '请输入您的用户名!',
            },
          ]}
        >
          <Input prefix={<UserOutlined className="site-form-item-icon" />} placeholder="Username" />
        </Form.Item>
        <Form.Item
          name="password"
          rules={[
            {
              required: true,
              message: '请输入您的密码!',
            },
          ]}
        >
          <Input
            prefix={<LockOutlined className="site-form-item-icon" />}
            type="password"
            placeholder="Password"
          />
        </Form.Item>
        <Form.Item
          name="captcha"
          rules={[
            {
              required: true,
              message: '请输入验证码!',
            },
          ]}
        >
          <Space>
            <Input prefix={<SyncOutlined />} placeholder="请输入验证码" />
            <Captcha ref={capRef} setKey={setKey} />
          </Space>

        </Form.Item>



        <Form.Item>
          <Button type="primary" htmlType="submit" className="login-form-button">
            登录
          </Button>
        </Form.Item>
      </Form>
    </div>
  )
}
